package books.ThinkingInJava.src.Chapter18;

import books.ThinkingInJava.src.Tools.FileKit;
import books.ThinkingInJava.src.Tools.Output;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author bloodcolding
 * @since 12/28/2018 6:52 PM
 */
public class TestChannel {

    public static void main(String[] args) throws IOException {
        String path = FileKit.filePathTransfer("D:\\Doc\\Test\\a.txt");
        FileChannel out = new FileOutputStream(path).getChannel();
        out.write(ByteBuffer.wrap("Save the text1".getBytes()));
        out.close();

        out = new RandomAccessFile(path, "rw").getChannel();
        ByteBuffer buff = ByteBuffer.allocate(2048);
        out.read(buff);
        buff.flip();
//        while (buff.hasRemaining()) {
//            System.out.println((char) buff.get());
//        }
        //读取字节数据后进行转码
        System.out.println(buff.asCharBuffer().toString());
        buff.rewind();  //重新从buffer头开始
        String encolding = System.getProperty("file.encoding");
        System.out.println("encoding:  " + encolding);
        System.out.println(Charset.forName(encolding).decode(buff)); //
        out.close();

        //使用字符进行写入
        out = new FileOutputStream(path).getChannel();
        out.write(ByteBuffer.wrap("Some text2.".getBytes(StandardCharsets.UTF_16BE)));
        out.close();
        out = new FileInputStream(path).getChannel();
        buff.clear();
        out.read(buff);
        buff.flip();
        Output.println(buff.asCharBuffer());

        //使用同一个buff进行输出输入，上面使用static方法
        out = new FileOutputStream(path).getChannel();
        buff.asCharBuffer().put("Some text3.");
        out.write(buff);
        out.close();
        out = new FileInputStream(path).getChannel();
        buff.clear();
        out.read(buff);
        buff.flip();
        Output.println(buff.asCharBuffer());
        Output.println(buff.getChar(1));
        out.close();

        //使用MappedBuffer进行输入输出
        out = new RandomAccessFile(new File(path), "rw").getChannel();
        CharBuffer cbuff = out.map(FileChannel.MapMode.READ_WRITE, 0, 1000).asCharBuffer();
        for (int i = 0; i < 50; i++) {
            cbuff.put((char) i);
        }
        out.close();

//        buff.reset();
//        out.read(buff);
//        buff.flip();
//        int i = 0;
//        while ((i = buff.getInt()) != -1){
//            Output.print(i);
//        }

    }
}

